<?php

namespace app\admin\controller;

use support\Request;
use app\common\Attribute;
use app\model\Menu;
use app\common\View;
use app\model\Attachment;
use app\model\Admin;
use Symfony\Component\Console\Helper\Dumper;

#[Attribute(title: "首页")]
class IndexController
{
    #[Attribute(isAuth: false, isPage: true, title: "首页")]
    public function index(Request $request)
    {
        return View::fetch();
    }

    #[Attribute(isAuth: false, isPage: true, title: "控制台")]
    public function console(Request $request)
    {
        return "欢迎使用";
    }

    #[Attribute(isAuth: false, isPage: true, title: "基本资料")]
    public function basicsInfo(Request $request)
    {
        $User = session('user');
        if (!isset($User)) {
            return error('非法请求', route('admin.login.log'));
        } else {
            $find = Admin::find($User["id"]);
            View::assign("find", $find);
        }
        if ($request->method() == "POST") {
            $all = $request->all();
            if ($all["id"] != $User['id']) {
                return error('非法操作', route('admin.login.log'));
            }
            try {
                validate("Admin", 'basicsInfo', $all);
                if (isset($all["password"])) {
                    unset($all["password"]);
                }
                $res = Admin::update($all);
                if ($res) {
                    return success("操作成功");
                } else {
                    return error("操作失败");
                }
            } catch (\think\exception\ValidateException $e) {
                return error(msg: "验证失败", data: $e->getError());
            }
        }
        return View::fetch();
    }

    #[Attribute(isAuth: false, isPage: true, title: "修改密码")]
    public function editPwd(Request $request)
    {
        $User = session('user');
        if (!isset($User)) {
            return error('非法请求', route('admin.login.log'));
        }
        if ($request->method() == "POST") {
            $all = $request->all();
            try {
                validate("Admin", 'editPwd', $all);
                $all["newPwd"] = password_hash($all["newPwd"], PASSWORD_DEFAULT);
                $res = Admin::update(["id" => $User['id'], "password" => $all["newPwd"]]);
                if ($res) {
                    return success("操作成功");
                } else {
                    return error("操作失败");
                }
            } catch (\think\exception\ValidateException $e) {
                return error(msg: "验证失败", data: $e->getError());
            }
        }
        return View::fetch();
    }

    #[Attribute(isAuth: false, isPage: false, title: "菜单")]
    public function menu(Request $request)
    {
        $res = Menu::where("status", "normal")->order("weigh", "desc")->select()->toArray();
        $UserAuth = session('auth');
        $arr = [];
        if ($UserAuth["rid"] > 0) {
            $AuthArr = json_decode($UserAuth["auth"], true); //已拥有的权限
            foreach ($res as $k => $v) {
                if ($v['controller'] == "" || in_array($v['controller'] . "@" . $v["method"], $AuthArr)) {
                    $arr[] = $v;
                }
            }
        } else {
            $arr = $res;
        }
        return success(data: buildTree($arr));
    }

    #[Attribute(isAuth: false, isPage: false, title: "清理缓存")]
    public function clearUrl(Request $request)
    {
        $path = runtime_path("views");
        if (file_exists($path)) {
            // 删除文件夹
            deleteFolder($path);
        }
        return success("清理成功");
    }

    #[Attribute(isAuth: false, isPage: false, title: "附件列")]
    public function files(Request $request)
    {
        if ($request->method() == "POST") {
            $all = $request->all();
            $data = Attachment::order("id", "desc")->paginate([
                "page" => $all["page"],
                "list_rows" => $all["limit"]
            ]);
            return json($data->toArray());
        }
    }

    #[Attribute(isAuth: false, isPage: false, title: "上传文件")]
    public function upload(Request $request)
    {
        if ($request->method() == "POST") {
            $files = $request->file();
            $category = $request->post("category"); //标签
            $arr = [];

            foreach ($files as $k => $v) {
                if ($v->isValid()) {
                    $fileName = '/files' . '/' . date("Ymd") . '/' . uniqid("kllxs_", true) . '.' . $v->getUploadExtension();
                    $data = [
                        "category" => $category,
                        "name" => $v->getUploadName(),
                        "url" => $fileName,
                        "type" => $v->getUploadMimeType(),
                        "size" => number_format($v->getSize() / 1048576, 2),
                        "spec" => $v->getUploadExtension(),
                        "storage" => "local"
                    ];
                    $file = $v->move(public_path() . $fileName);
                    if ($file) {
                        $res = Attachment::create($data);
                        if ($res) {
                            $arr = [
                                'code' => 1,
                                'msg' => "上传成功",
                                'url' => $fileName,
                                'data' => $v
                            ];
                        } else {
                            $arr = [
                                'code' => 2,
                                "msg" => "文件写入失败",
                                "data" => $v,
                                "error" => $file
                            ];
                        }
                    } else {
                        $arr = [
                            'code' => 2,
                            "msg" => "文件上传失败",
                            "data" => $v,
                            "error" => $file
                        ];
                    }
                } else {
                    $arr = [
                        'code' => 2,
                        "msg" => "文件无效",
                        "data" => $v
                    ];
                }
            }
            return json($arr);
        }
    }
}
